import java.io.*;
import java.util.Scanner;

public class Copy {
    public static void main(String[] args) throws IOException {
        //1.请求输入  文件  路径
        System.out.println("请输入文件目录：");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        //创建文件对象
        File CopyFile = new File(s);
        //2.判断路径书否有效
        if(!CopyFile.exists()) {
            System.out.println("输入路径为空");
            return;
        }
        if(!CopyFile.isFile()) {
            System.out.println("输入的路径有误，不可以是目录");
            return;
        }
        //请求输入要复制到的文件路径
        System.out.println("请输入复制的路径：");
        String s1 = scanner.nextLine();
        File CopyToFile = new File(s1);
        //检索目录是否有效
        if(CopyToFile.exists()) {
            System.out.println("输入的路径已存在");
            return;
        }
        if(!CopyToFile.getParentFile().exists()) {
            System.out.println("目录的父目录不存在");
            return;
        }
        //进行读写文件
        copyTo(CopyFile,CopyToFile);
        scanner.close();
    }

    private static void copyTo(File copyFile, File copyToFile) throws IOException {
        //创建输入输出流
        //创建输入流
        //Scanner scanner = new Scanner(fileInputStream);
        //创建输出流
        //PrintWriter printWriter = new PrintWriter(fileOutputStream);
        //进行读写
//        while(scanner.hasNextLine()) {
//            //读一句写一句
//            String copy = scanner.nextLine();
//            printWriter.println(copy);
//            fileOutputStream.flush();
//        }
//        //关闭流
//        fileInputStream.close();
//        fileOutputStream.close();
//        scanner.close();
        try (FileInputStream InputStream = new FileInputStream(copyFile);
             FileOutputStream OutputStream = new FileOutputStream(copyToFile);){
            byte [] bytes = new byte[1024];
            while (true) {
                int len = InputStream.read(bytes);
                if(len == -1) {
                    break;
                }
                OutputStream.write(bytes);
            }
            OutputStream.flush();
            System.out.println("复制成功");
        }
    }
}
